<template>
    <div>
        <NavTop />
        <div style="width: 1400px; margin: auto;">
            <el-table ref="multipleTableRef" :data="filteredCartData" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" :selectable="selectable" width="55" />
                <el-table-column property="id" label="商品编号" width="150" />
                <el-table-column property="name" label="商品名称" width="350" />
                <el-table-column property="onlineprice" label="价格" width="120" />
                <el-table-column property="num" label="数量" width="120" />
                <el-table-column property="total" label="总金额" width="250" />
                <el-table-column align="right">
                    <template #header>
                        <el-input v-model="search" size="small" placeholder="Type to search" @input="filterCartData" />
                    </template>
                    <template #default="scope">
                        <el-button
                            size="small"
                            type="danger"
                            @click="confirmDelete(scope.$index)"
                        >
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div style="margin-top: 20px;">
                <el-button @click="confirmBuy">购买</el-button>
            </div>
        </div>
    </div>
</template>

<script>
import { useGoodsStore } from '@/store/goods';
import NavTop from '../../components/NavTop';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
    components: {
        NavTop
    },
    data() {
        return {
            multipleTableRef: null,
            multipleSelection: [],
            store: useGoodsStore(),
            cartData: JSON.parse(sessionStorage.getItem('cart')) || [],
            filteredCartData: [],
            search: '',
            time: new Date(),
            orderID: ''
        };
    },
    methods: {
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        filterCartData() {
            if (this.search === '') {
                this.filteredCartData = this.cartData;
            } else {
                this.filteredCartData = this.cartData.filter(item => {
                    return item.name.toLowerCase().includes(this.search.toLowerCase());
                });
            }
        },
        confirmDelete(index) {
            ElMessageBox.confirm('是否删除该商品？', '确认删除', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.cartData.splice(index, 1);
                this.filterCartData();
                sessionStorage.setItem('cart', JSON.stringify(this.cartData));
            }).catch(() => {
                ElMessage.info('已取消删除');
            });
        },
        confirmBuy() {
            if (this.multipleSelection.length === 0) {
                ElMessageBox.alert('请选择你要购买的商品', '提示', {
                    confirmButtonText: '确定'
                });
                return;
            }
            ElMessageBox.confirm('是否购买这些商品？', '确认购买', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'question'
            }).then(() => {
                this.orderID = this.time.getFullYear().toString() + (this.time.getMonth() + 1).toString() +
                    this.time.getDate().toString() + Math.random().toString().slice(2, 10);
                let num = 0;
                let sum = 0;
                this.multipleSelection.forEach(v => {
                    num += v.num;
                    sum += parseInt(v.total);
                });
                this.store.orderAdd({
                    orderID: this.orderID,
                    time: this.time,
                    num: num,
                    sum: sum,
                    isOrdered: false,
                    child: [...this.multipleSelection]
                });
                this.multipleSelection.forEach((list) => {
                    const x = this.cartData.findIndex((item) => list.id === item.id);
                    if (x!== -1) {
                        this.cartData.splice(x, 1);
                    }
                });
                this.filterCartData();
                sessionStorage.setItem('cart', JSON.stringify(this.cartData));
                ElMessage.success('已购买');
            }).catch(() => {
                ElMessage.info('已取消购买');
            });
        }
    },
    mounted() {
        this.filteredCartData = this.cartData;
    }
};
</script>